import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/pay_type_model.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/emuns/pay_type_enum.dart';
import 'package:flutter_deer/ui/cashier/dialog/diaog_card_pay.dart';
import 'package:flutter_deer/ui/cashier/dialog/order_pay_mobile_dialog.dart';
import 'package:flutter_deer/ui/cashier/dialog/sort_drag_dialog.dart';
import 'package:flutter_deer/ui/cashier/item/cashier_pay_type_item.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/dialog/error_dialog.dart';
import 'package:flutter_deer/widgets/dialog/pay_success_dialog.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:get/get.dart';


class CashierPayTypePage extends StatefulWidget {
  const CashierPayTypePage({super.key});

  @override
  State<CashierPayTypePage> createState() => _CashierPayTypePageState();
}

class _CashierPayTypePageState extends State<CashierPayTypePage> {
  static const double paddingPayType = 5.0;
  final mProvider = Get.find<CashierPageProvider>();

  @override
  void initState() {
    super.initState();
    PayTypeModel.getAll().then((value) {
      setState(() {
        mProvider.mALlListPayType.assignAll(value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() => Stack(children: [

          // 支付方式
          Container(
            decoration: const BoxDecoration(
              color: Colours.white,
            ),
            // height: 276,
            padding: const EdgeInsets.all(paddingPayType),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 固定高度的网格视图，最多显示6个项目
                Expanded(
                      // color: Colors.white,
                      // height: 250, // 每个项目高度80，最多6个项目
                      child: GridView.builder(
                        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2, // 每行2个项目
                          childAspectRatio: 1.4, // 宽高比
                          crossAxisSpacing: paddingPayType, // 列间距
                          mainAxisSpacing: paddingPayType, // 行间距
                        ),
                        itemCount: mProvider.mALlListPayType.where((e) => e.switchConsumePay).length,
                        itemBuilder: (context, index) {
                          final item = mProvider.mALlListPayType.where((e) => e.switchConsumePay).toList()[index];
                          return CashierPayTypeItem(
                            item: item,
                            onTap: () {
                              mProvider.selectPayType(item);
                              // [储值卡]
                              if (item.paymentCode == PayTypeEnum.Card.paymentCode) {
                                _showCardPayDialog();
                              }
                            },
                            onLongPress: () {
                              _showPayTypeSortDialog();
                            },
                          );
                        },
                      ),
                    ),
                const SizedBox(height: 4),
                PressBlueButton(
                      height: 40,
                      fontSize: 16,
                      hoverColor: Colors.redAccent.withOpacity(0.5),
                      defaultColor: Colors.redAccent,
                      text: mProvider.getPayText(),
                      onLongPress: () {
                        _showPayTypeSortDialog();
                      },
                      onPressed: () {
                        if (!mProvider.canClickPayType()) {
                          Toast.show('请先选商品');
                          return;
                        }

                        // [移动]
                        if (mProvider.mPayTypeRx.value?.isMobilePay() ?? false) {
                          mProvider.calculateQrCode(onSuccessCallBack: (msg) {
                            showDialog<void>(
                              context: context,
                              builder: (BuildContext context) {
                                return OrderPayMobileDialog(msg);
                              },
                            );
                          });
                          return;
                        }

                        // [混合]
                        if (mProvider.mPayTypeRx.value?.paymentCode == PayTypeEnum.MIX.paymentCode) {
                          showErrorDialog('功能开发中，敬请期待！');
                          return;
                        }

                        // [储值卡]
                        if (mProvider.mPayTypeRx.value?.paymentCode == PayTypeEnum.Card.paymentCode) {
                          _showCardPayDialog();
                          return;
                        }

                        // [支付]
                        mProvider.orderPay(
                          onSuccess: (data, successInfo) {
                            showPaySuccessDialog(successInfo);
                          },
                          onError: (msg) {
                            showErrorDialog(msg);
                          },
                        );
                      },
                    ),
              ],
            ),
          ),

        ]));
  }

  // 展示支付方式排序弹窗
  void _showPayTypeSortDialog() {
    showDialog<void>(
      context: context,
      builder: (context) => SortDragListDialog(
        title: '支付方式开关与排序',
        items: mProvider.mALlListPayType,
        onConfirmed: (selectedItems) {
          for (int i = 0; i < selectedItems.length; i++) {
            selectedItems[i].mSortNo = i;
          }
          mProvider.mALlListPayType.value = selectedItems;
          PayTypeModel.saveAll(selectedItems).then((_) {
            print('支付方式更新成功');
          });
          Navigator.of(context).pop();
        },
      ),
    );
  }

  void showPaySuccessDialog(String successInfo) {
    mProvider.reset();
    showDialog<void>(
      context: context,
      barrierDismissible: false, // 禁止点击背景关闭
      builder: (context) {
        return PaySuccessDialog(
          successInfo: successInfo,
          onConfirm: () {
            // 执行确认操作，例如跳转页面或刷新数据
            print('支付成功，3秒后执行确认');
          },
        );
      },
    );
  }

  void showErrorDialog(String msg) {
    showDialog<void>(
      context: context,
      builder: (context) => ErrorDialog(
        errorMessage: msg,
        onConfirm: () {
          // 处理确认按钮的逻辑
        },
      ),
    );
  }

  void _showCardPayDialog() {
    mProvider.refreshDiscount(successCallback: (list){
      if (list.isEmpty) {
        return;
      }
      mProvider.mCardList.assignAll(list);
      showDialog<void>(
        context: context,
        barrierDismissible: false, // 点击背景不消失
        builder: (BuildContext context) {
          return AlertDialog(
            contentPadding: EdgeInsets.zero,
            content: SizedBox(
              width: MediaQuery.of(context).size.width * 0.6,
              height: MediaQuery.of(context).size.height * 0.7,
              child: const DialogCardPay(),
            ),
          );
        },
      );
    });
  }
}
